package com.rede.didiok.user.service.impl;


import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rede.didiok.common.utils.ResultUtil;
import com.rede.didiok.common.utils.business.DomainEventUtil;
import com.rede.didiok.user.modulelist.pay.dao.PayOrderDao;
import com.rede.didiok.user.modulelist.pay.global.SysConf;
import com.rede.didiok.user.modulelist.pay.model.bean.LanTuWxPayBean;
import com.rede.didiok.user.modulelist.pay.service.PayOrderService;
import com.rede.didiok.user.modulelist.pay.utils.LantuPayUtil;
import com.rede.didiok.user.service.LantuWechatService;

/**
 * 第三方微信支付服务
 *
 * @author 陌溪
 */
@Slf4j
@Service("lantuWechatService")
public class LantuWechatServiceImpl implements LantuWechatService {

    @Resource
    private PayOrderService payOrderService;

    @Resource
    private PayOrderDao payOrderDao;

    @Resource
    private LanTuWxPayBean lanTuWxPayBean;

    @Resource
    private DomainEventUtil domainEventUtil;


    private static final String LANTU_GET_WECHAT_OPEN_ID = "https://api.ltzf.cn/api/wxpay/get_wechat_openid";

    //蓝兔授权成功后的重定向的回调链接地址
//    private static final String LANTU_CALLBACK_URL = "/h5Login/callback";

    @Override
    public String getWechatOpenIdUrl(String attach, String callbackUrl) {

        String mchId = lanTuWxPayBean.getMchId();
        String timestamp = String.valueOf(System.currentTimeMillis()/1000);
        String sign = LantuPayUtil.createSignByGetOpenId(mchId, timestamp, callbackUrl);
        StringBuilder orderStr = new StringBuilder();
        orderStr.append("mch_id=").append(mchId)
                .append("&timestamp=").append(timestamp)
                .append("&callback_url=").append(callbackUrl)
                .append("&sign=").append(sign);
        if(null != attach) {
            orderStr.append("&attach=").append(attach);
        }

        log.info("蓝兔 get_wechat_openid 请求数据：{}", orderStr.toString());
        HttpResponse<String> response = Unirest.post(LANTU_GET_WECHAT_OPEN_ID)
                .header("content-type", "application/x-www-form-urlencoded; charset=UTF-8")
                .body(orderStr.toString())
                .asString();

        log.info("蓝兔 get_wechat_openid 响应结果：{}", JSON.toJSONString(response));
        if(null != response && 200 == response.getStatus()){
            String body = response.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            Integer code = (Integer) jsonObject.get("code");
            // code  0：成功  1：失败
            if(code != null && code == 0){
                String openIdUrl = jsonObject.get("data").toString();
                return openIdUrl;
            }else{
                log.info("get_wechat_openid 失败：{}",jsonObject.get("msg").toString());

            }
        }

        return null;
    }

    @Override
    public String getWechatUserInfo(String codeStr) {

        String mchId = lanTuWxPayBean.getMchId();
        String timestamp = String.valueOf(System.currentTimeMillis()/1000);

        String sign = LantuPayUtil.createSignByGetOpenId(mchId, timestamp, codeStr);
        StringBuilder orderStr = new StringBuilder();
        orderStr.append("mch_id=").append(mchId)
                .append("&timestamp=").append(timestamp)
                .append("&code=").append(codeStr)
                .append("&sign=").append(sign)
        ;
        log.info("蓝兔 get_wechat_openid 请求数据：{}", orderStr.toString());
        HttpResponse<String> response = Unirest.post(LANTU_GET_WECHAT_OPEN_ID)
                .header("content-type", "application/x-www-form-urlencoded; charset=UTF-8")
                .body(orderStr.toString())
                .asString();

        log.info("蓝兔 get_wechat_openid 响应结果：{}", JSON.toJSONString(response));
        if(null != response && 200 == response.getStatus()){
            String body = response.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            Integer code = (Integer) jsonObject.get("code");
            // code  0：成功  1：失败
            if(code != null && code == 0){
                String openIdUrl = jsonObject.get("data").toString();

                Map<String, String> resultMap = new HashMap<>();
                resultMap.put(SysConf.URL, openIdUrl);
                return ResultUtil.successWithData(resultMap);
            }else{
                log.info("get_wechat_openid 失败：{}",jsonObject.get("msg").toString());
            }
        }

        return ResultUtil.errorWithMessage("get_wechat_openid失败！");
    }

}
